/**
* Field consumer that shows the value of specified attribute to GUI
**/
jsx3.Class.defineClass(
	"ux.cdb.admin.dataautomate.AreaUpdater",
	ux.cdb.admin.dataautomate.GenericUpdater, null,
	function (block) {
		
		var docArea = null; //document database for area code.
		var selects = null; //array for select box
		
		/**
		* instance initializer
		* @param strName {String} unique name distinguishing this object from all other JSX GUI objects in the JSX application
		* @param vntLeft {int|String} either a number (i.e, 12, 30, etc) or a number and a unit value (i.e., "25%", "36pt", etc); if a number is passed, pixels will be the assumed unit when painted to screen
		* @param vntTop {int|String} either a number (i.e, 12, 30, etc) or a number and a unit value (i.e., "25%", "36pt", etc); if a number is passed, pixels will be the assumed unit when painted to screen
		* @param vntWidth {int|String} either a number (i.e, 12, 30, etc) or a number and a unit value (i.e., "25%", "36pt", etc); if a number is passed, pixels will be the assumed unit when painted to screen
		* @param vntHeight {int|String} either a number (i.e, 12, 30, etc) or a number and a unit value (i.e., "25%", "36pt", etc); if a number is passed, pixels will be the assumed unit when painted to screen
		* @param strHTML {String} Text/HTML markup to place in the jsx3.gui.Block instance
		*/
		block.prototype.init = function(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML) {
			//call constructor for super class (the super expects the name of the object and the function that it is an instance of)
			this.jsxsuper(strName, vntLeft, vntTop, vntWidth, vntHeight, strHTML);
		};

		block.prototype.onAfterPaint = function(){
			this.initialize();
		};
		
		
		block.prototype.initialize = function(){
			docArea = jsx3.xml.CDF.Document.newDocument();
			docArea.load(ux.megatron.Main.getServer().resolveURI('jsxaddin://user!cdbadmin/xml/Areas.xml'));
			ux.megatron.Main.getServer().getCache().setDocument('Area_doc',docArea);
			//ux.megatron.Main.getServer().getCache().openDocument(ux.megatron.Main.getServer().resolveURI('jsxaddin://user!cdbadmin/xml/Areas.xml'),'Area_doc',jsx3.xml.CDF.Document);
			
			if(jsx3.ide) { return; }
			
			this._defaultText = ux.megatron.Main.getServer().getDynamicProperty("@cdb@AreaSelect Default Text");

			//set event code
			selects = this.getDescendantsOfType('jsx3.gui.Select');	
			for(var i=0;i<selects.length;i++){
				var sel = selects[i];
				sel.setEvent('this.getAncestorOfType("ux.cdb.admin.dataautomate.AreaUpdater").onSelectChanged(this);',jsx3.gui.Interactive.SELECT);
			}
			
			this.onSelectChanged(null);
		};
		
		block.prototype.applyData = function(data) {
			//alert("need to be overrided");
			var me = this;
			var val = data[this.uxdataatt];
			if(!val) return;
			//console.log(docArea);
			/* e.g. val : 500000, 500100, 500101,  */
			try{
				var sel1Record, sel2Record, sel3Record;
				if(val.lastIndexOf('0000') == 2){
					sel1Record = docArea.getRecordNode(val);
				}else if(val.lastIndexOf('00') == 4){
					sel2Record = docArea.getRecordNode(val);
					sel1Record = sel2Record.getParent();
				}else{
					sel3Record = docArea.getRecordNode(val);
					sel2Record = sel3Record.getParent();
					sel1Record = sel2Record.getParent();
				}
			}catch(ex){
				throw 'You specified a error area code ,the code is not exists,code is:'+val;
			}

			//console.log('sels,from 1,2,3:',sel1Record,sel2Record,sel3Record);
			//Bull shit code,just for working....lost my face.
			var selDoc,children,child;
			var selects = this.getDescendantsOfType('jsx3.gui.Select');
			for(var i=0;i<selects.length;i++){
				var sel = selects[i];
				var scriptEvent = sel.getEvent(jsx3.gui.Interactive.SELECT);
				var recordNode = eval('sel'+(i+1).toString()+'Record');
				if(i == 0){
					sel.setValue(recordNode.getAttribute('jsxid'));
				}else{
					selDoc = jsx3.xml.CDF.Document.newDocument();
					children = recordNode.getParent().getChildNodes();					
					for(j=0;j<children.size();j++){
						child = children.get(j).cloneNode(false);
						selDoc.insertRecordNode(child);
					}					
					sel.setSourceXML(selDoc);
					sel.setValue(recordNode.getAttribute('jsxid'),true);
				}
				sel.setEvent(scriptEvent,jsx3.gui.Interactive.SELECT);
				this.onSelectChanged(sel);
			}
		};

		block.prototype.extractData = function(){
			//return this.getDescendantOfName("selValue1").getValue() + ',' + this.getDescendantOfName("selValue2").getValue() + ',' + this.getDescendantOfName("selValue3").getValue();
			if(this._defaultText.indexOf(this.getDescendantOfName("selValue2").getText()) > -1
				&& this._defaultText.indexOf(this.getDescendantOfName("selValue3").getText()) > -1)
				return this.getDescendantOfName("selValue1").getValue();
			else if(this._defaultText.indexOf(this.getDescendantOfName("selValue3").getText()) > -1)
				return this.getDescendantOfName("selValue2").getValue();
			else
				return this.getDescendantOfName("selValue3").getValue();
		};
		
		block.prototype.onSelectChanged = function(objSel){
			var selects = this.getDescendantsOfType('jsx3.gui.Select');
            var selDoc, children, j, child;
			
			for(var i=0;i<selects.length;i++){
				//remove select event to prevent the execution of on select script
				var sel = selects[i];
				var scriptEvent = sel.getEvent(jsx3.gui.Interactive.SELECT);
				sel.removeEvent(jsx3.gui.Interactive.SELECT);
				
				if(i===0 && sel.getXML().getChildNodes().size()===0){
					//initial first select
					selDoc = jsx3.xml.CDF.Document.newDocument();
					children = docArea.getChildNodes();					
					for(j=0;j<children.size();j++){
						child = children.get(j).cloneNode(false);
						selDoc.insertRecordNode(child);
					}					
					sel.setSourceXML(selDoc);
					
					sel.setValue(selDoc.getFirstChild().getAttribute('jsxid'),true);
				}

				if(i !== 0){
					
					
					var rec = docArea.getRecordNode(sel.getValue());
					var parent = null;
					if(rec === null){
						//init current select
						parent = null;
					}else{
						parent = rec.getParent();
					}
					if(this._defaultText.indexOf(selects[i-1].getText()) == -1 || this._defaultText.indexOf(sel.getText()) == -1) {
						if(parent === null || (parent !== null && parent.getAttribute('jsxid') != selects[i-1].getValue())){
							selDoc = jsx3.xml.CDF.Document.newDocument();
							children = docArea.getRecordNode(selects[i-1].getValue()).getChildNodes();	
							
							for(j=0;j<children.size();j++){
								child = children.get(j).cloneNode(false);
								selDoc.insertRecordNode(child);
							}					
							sel.setSourceXML(selDoc);
							sel.setValue(selDoc.getFirstChild().getAttribute('jsxid'),true);
						}
					} else {
						selDoc = jsx3.xml.CDF.Document.newDocument();
						selDoc.insertRecord({jsxid:"0000000", jsxtext:this._defaultText});
						sel.setSourceXML(selDoc);
						sel.setValue(selDoc.getFirstChild().getAttribute('jsxid'),true);					
					}
				}

				//restore select event to prevent the execution of on select script
				sel.setEvent(scriptEvent,jsx3.gui.Interactive.SELECT);
				
			}
		};
		
				//methods from IExtractor interface for support validation correctly
		block.prototype._validateFailedUI = function(failed,message){
			var sels = [];

			sels.push(this.getDescendantOfName("selValue1"));
			sels.push(this.getDescendantOfName("selValue2"));
			sels.push(this.getDescendantOfName("selValue3"));
			
			for(var i=0;i<sels.length;i++){
				var sel = sels[i];
				if(failed === true){
					sel.setBackgroundColor(ux.megatron.Main.getServer().getDynamicProperty("@cdb@Validation Failed BGColor"), true);
					sel.setTip((message) ? message : "");
				}else{
					sel.setBackgroundColor("#FFFFFF", true);
					sel.setTip("");
				}
			}

		};

        block.prototype.focusField = function() {
            if(this.get("selValue1")) {
                this.get("selValue1").focus();
            }
        };
		
	});